package com.kabuda.zhugehot200;

/**
 * @author kabuda
 * @date 2025-03-15 16:47
 * @description
 */
public class t69_x的平方根 {
    public static void main(String[] args) {
        System.out.println(violence(2147395599));
        System.out.println(binarySearch(2147395599));
        System.out.println(newton(2147395599));
    }

    /**
     * 暴力破解
     *
     * @param x
     * @return
     */
    public static int violence(int x) {
        int result = 0;
        for (int i = 0; i < x; i++) {
            if (i * i <= x) {
                result = i;
            } else {
                return result;
            }
        }
        return result;
    }

    /**
     * 二分查找
     *
     * @param x
     * @return
     */
    public static int binarySearch(int x) {
        int result = 0;
        int left = 0;
        int right = x;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if ((long)mid*mid<=x&&mid * mid <= x) {
                result = mid;
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return result;
    }


    /**
     * 牛顿迭代
     *
     * @param x
     * @return
     */
    public static int newton(int x) {
      return recursion(x, x);
    }

    /**
     * 递归
     * @param n 近似平方根
     * @param x 被开方值
     * @return
     */
    public static int recursion(double n,int x) {
        double result= (n + x / n) / 2;
        if(result==n){
            return (int)result;
        }else {
            return recursion(result,x);
        }
    }
}
